package com.noahplat.oufu.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.noahplat.alarm.feign.AlarmFeign;
import com.noahplat.alarm.pojo.Alarm;
import com.noahplat.common.cusexception.RedisException;
import com.noahplat.common.utils.*;
import com.noahplat.datapro.pojo.*;
import com.noahplat.fence.pojo.Fence;
import com.noahplat.oufu.feign.OtherGetMapFeign;
import com.noahplat.oufu.feign.OtherMapFeign;
import com.noahplat.oufu.mapper.*;
import com.noahplat.oufu.service.RecvDataHandService;
import com.noahplat.oufu.utils.MQUtil;
import com.noahplat.user.feign.SconfigFeign;
import com.noahplat.user.pojo.Sconfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sun.misc.BASE64Decoder;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.util.IOUtils.DIGITS;

/**
 *功能：欧孚数据解析实现类
 * time:2021.02.24
 * name:宋彦磊
 */
@Service
public class RecvDataHandServiceImpl implements RecvDataHandService {
    @Autowired
    private OtherMapFeign otherMapFeign;
    @Autowired
    private OtherGetMapFeign otherGetMapFeign;
    @Autowired
    private AlarmFeign alarmFeign;
    @Autowired
    private SconfigFeign sconfigFeign;

    public static final String TOKEN = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6ImFkbWluIiwiYWNjdGlkIjoxLCJzdGlkIjoiMiIsInBpZCI6MSwiaWQiOjYsInVzZXJUeXBlIjoiMCIsImV4cCI6MTcxNjg3Mzc5MCwiYXV0aG9yaXRpZXMiOlsibm9haHBsYXQtc2VydmljZS1hbGFybTpBbGFybUNvbnRyb2xsZXI6YWRkQWxhcm0iXSwianRpIjoiZDdlYWUzYmUtOTg1ZS00NjVhLWJhNTEtZjg4OGY4ZjA5ZTI4IiwiY2xpZW50X2lkIjoibm9haHBsYXQiLCJ1c2VybmFtZSI6ImFkbWluIn0.JTcCn5q7rVNqO1TLY7WwD6LcCtnCeWqeL_8pym1AavwIL49s_6LCqUyN32bZDhMEnOGyW3CQcNxJrr4eMtvpox_xC2PRVvYDrAfKeAVSiPegCELmZPGIbpSVGsa-hyXPBx6EkslDCUmVFsAaTkvFJuwQiVZtS0Jb7D2qINmqg9rCkKqltzgEe0eeZW8t18XLUcj3D0A__7gPU-SOm9nbG4pUP6ydhSTL1ShNVvEkrnzf1RvKDlZfid7qTXiziqAgaiZZQA3lOVDo_hMf-5x6qrYnRtb9FH-CMgTg4syh1B9ch7Z1bbdA7sGNZnNcUthZStAy5R-uarIxYsiq-wbyng";
    public static final String GETMAKTOKEN="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6ImFkbWluIiwiYWNjdGlkIjoxLCJzdGlkIjoiMiIsInBpZCI6MSwiaWQiOjYsInVzZXJUeXBlIjoiMCIsImV4cCI6MTcxNjg3NDI2NCwiYXV0aG9yaXRpZXMiOlsibm9haHBsYXQtc2VydmljZS11c2VyOlNjb25maWdDb250cm9sbGVyOmdldE1hcG51bSJdLCJqdGkiOiJhM2Q2ZGQ3OC0wNTJkLTQ2YzItYmE5Ny0xNzIyYWIzYTUzOTgiLCJjbGllbnRfaWQiOiJub2FocGxhdCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.LFBcJh7AedaJ9OIH-_TQin8jscB9z-nMcAlqqRjQfU1TwgMnUira7DxpVBPp7FZjN-lEWR7Kf4w-0FIbuP2c2Ru5edJp09-NBpdJom9KfLxmd5DreZkFgtTvjUd3w7HZB7SpM4d4nhz5L3x_wBRQkg8eNxid83MXJoJl6qaxv_5a9xOIdQ2-mwW4dr4rqIX-QTb_RO7W0if5pQmG1VQNRt9aFlqhHEYvBx0h1xqxgCOyTqh1BzdCEuKadv1oQZcR_FnxWD-Myssm2nkOD4KUsQEeoDpJjHzV0_meOWN5a8Y3RsWpcVL9hbyklSvB__5JHAU7agV8q_mkEeA8ljTjFQ";
    public static final String UPDATEMAKTOKEN="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6WyJhcHAiXSwibmFtZSI6ImFkbWluIiwiYWNjdGlkIjoxLCJzdGlkIjoiMiIsInBpZCI6MSwiaWQiOjYsInVzZXJUeXBlIjoiMCIsImV4cCI6MTcxNjg3NDMxNSwiYXV0aG9yaXRpZXMiOlsibm9haHBsYXQtc2VydmljZS11c2VyOlNjb25maWdDb250cm9sbGVyOnVwZGF0ZU1hcG51bSJdLCJqdGkiOiI2MjNjYTA0Zi02Y2FmLTRlOTUtOGI3OC0wYjM0ZTI2ZWFlY2QiLCJjbGllbnRfaWQiOiJub2FocGxhdCIsInVzZXJuYW1lIjoiYWRtaW4ifQ.dGQd70e1o5KXxho3Zzv6ZmZxYjhJzgd30YpYb53y852mf55GWrpf-SVRElPcsOlenPFBepCxKygCnlTEMjOO5aF_9dQ377FnRss5Mfv582PB3LfKvnvZDoapG7Ty5gaBzQTcWTCuTTGdzQ_fhTWTCVPbIVO93AzXeiWxqPc6FWgDCYNPQ9JkUSINDH5Ojw8RISJJR6fTCzXzj6WkCjdIWjdNhPKi1OSRJaztyAgTgaM18uK_yk-CX_HUFmo-HUzVIIuUErgkZ98dqNIyKY4fJcn4f-Wrhn1OY3tX4J_A8GQfefJqV2BUUfG9PSVtvPA3h9mWHhrTDlq0US7k8lJj8A";
    @Autowired
    private BloodMapper bloodMapper;
    @Autowired
    private SiteMapper siteMapper;
    @Autowired
    private StepMapper stepMapper;
    @Autowired
    private HeartMapper heartMapper;
    @Autowired
    private TempMapper tempMapper;
    @Autowired
    private DstatusMapper dstatusMapper;
    @Autowired
    private SpMapper spMapper;
    @Autowired
    private SemaphoreMapper semaphoreMapper;
    @Autowired
    private SleepMapper sleepMapper;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MQUtil mqUtil;


    @Override
    public void recvDataHand(String msg){
         JSONObject backmsg = JSON.parseObject(msg);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//转换时间戳
        String imei = backmsg.getString("IMEI");//json串获得设备唯一标识
        String data = backmsg.getJSONObject("payload").getJSONObject("serviceData").getString("upOptData");//获得加密的数据
        String time = backmsg.getString("timestamp");//获得时间戳
        try{

            Date date = new Date();

            //开始解析数据
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] str = decoder.decodeBuffer(data);//base64加密解密
            final StringBuffer sb = new StringBuffer(str.length * 2);
            //转成16进制字符串
            for (int i = 0; i < str.length; i++) {
                sb.append(DIGITS[(str[i] >>> 4) & 0x0F]);
                sb.append(DIGITS[str[i] & 0x0F]);
            }
            String[] back = sb.toString().split("BDBDBDBD");
            for(String backdate : back){
                if(StringUtils.isEmpty(backdate) || backdate.equals("0")){
                    continue;
                }
                String keyname = backdate.substring(0,2);
                if(keyname.equals("D6")){
                    System.out.println("backdate = " + backdate);
                }
                if(keyname.equals("C1")){
                    //解析血糖结果
                    BigInteger bigInteger = new BigInteger(backdate.substring(2,4),16);
                    int i = bigInteger.intValue()/10;
                    String sugar = String.valueOf(i);
                }else if(keyname.equals("C2")){
                    //解析心率和血压
                    BigInteger bigInteger = new BigInteger(backdate.substring(4,6)+backdate.substring(2,4),16);
                    String systolic = String.valueOf(bigInteger.intValue());//收缩压
                    BigInteger bigInteger1 = new BigInteger(backdate.substring(8,10)+backdate.substring(6,8),16);
                    String diastolic = String.valueOf(bigInteger1.intValue());//舒张压
                    BigInteger bigInteger2 = new BigInteger(backdate.substring(12,14)+backdate.substring(10,12),16);
                    String heart = String.valueOf(bigInteger2.intValue());//心率
                    //血压加载
                    if(!systolic.equals("0") || !diastolic.equals("0")){
                        Blood blood = new Blood();
                        blood.setBlood(systolic+","+diastolic);
                        blood.setImei(imei);
                        blood.setTs(date);
                        blood.setModel("B2315+");
                        blood.setProd("OUFU");
                        int i = bloodMapper.insert(blood);
                    }

                    if(!heart.equals("0")){
                        Heart heart1 = new Heart();
                        heart1.setHeart(heart);
                        heart1.setImei(imei);
                        heart1.setModel("B2315+");
                        heart1.setProd("OUFU");
                        heart1.setTs(date);
                        int i1 = heartMapper.insert(heart1);
                    }
                }else if(keyname.equals("B6")){
                    //解析气温
                    BigInteger bigInteger = new BigInteger(backdate.substring(2,4),16);
                    int i = bigInteger.intValue()/10;
                    String air = String.valueOf(i);

                }else if(keyname.equals("BA")){
                    //多种温度解析
                    BigInteger bigInteger = null;
                    BigInteger bigInteger1 = null;
                   if(backdate.substring(2,4).equals("01")) {
                       bigInteger = new BigInteger(backdate.substring(8,10)+backdate.substring(6,8),16);
                       bigInteger1 = new BigInteger(backdate.substring(12,14)+backdate.substring(10,12),16);
                    }else {
                       bigInteger = new BigInteger(backdate.substring(16,18)+backdate.substring(14,16),16);
                       bigInteger1 = new BigInteger(backdate.substring(20,22)+backdate.substring(18,20),16);
                   }
                    float b = bigInteger.intValue();
                    String bodytemp = String.valueOf(b/10);
                    float a = bigInteger1.intValue();
                    if(a == 0){
                        continue;
                    }
                    String temp = String.valueOf(a/10);
                    Temp temp1 = new Temp();
                    temp1.setImei(imei);
                    temp1.setModel("B2315+");
                    temp1.setProd("OUFU");
                    temp1.setTemp(temp);
                    temp1.setTs(date);
                    int i = tempMapper.insert(temp1);

                }else if(keyname.equals("03")){
                    //坐标解析
                    BigInteger bigInteger = new BigInteger(backdate.substring(16,18)+backdate.substring(14,16)+backdate.substring(12,14)+
                            backdate.substring(10,12)+backdate.substring(8,10)+backdate.substring(6,8)+backdate.substring(4,6)+
                            backdate.substring(2,4),16);
                    String longitude = String.valueOf(bigInteger.intValue());//经度
                    BigInteger bigInteger1 = new BigInteger(backdate.substring(32,34)+backdate.substring(30,32)+backdate.substring(28,30)+
                            backdate.substring(26,28)+backdate.substring(24,26)+backdate.substring(22,24)+backdate.substring(20,22)+
                            backdate.substring(18,20),16);
                    String latitude = String.valueOf(bigInteger1.intValue());//纬度
                    String s = longitude+","+latitude;

                    //动态去mapkey值
                    boolean keyres = redisUtils.hasKey(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSKEY.getCode());
                    if(!keyres){
                        Result result = sconfigFeign.getMapnum("1","Bearer "+GETMAKTOKEN);
                        if(!result.isFlag()){
                            continue;
                        }
                        Map map = (Map) result.getData();
                        Sconfig sconfig1 = new Sconfig();
                        sconfig1.setId(Long.parseLong(map.get("id").toString()));
                        sconfig1.setMapkey(map.get("mapkey").toString());
                        sconfig1.setState( map.get("state").toString());
                        sconfig1.setType(map.get("type").toString());
                        boolean res = redisUtils.set(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSKEY.getCode(),sconfig1);
                        if(!res){
                            continue;
                        }
                    }
                    Object object = redisUtils.getValue(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSKEY.getCode());
                    Sconfig sconfig = (Sconfig) object;
                    Long number  = redisUtils.incr(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSNUMKEY.getCode(),1);
                    String mapkey = sconfig.getMapkey();
                    if(number > 2900000){
                        redisUtils.lock(NoahEnum.GPSLOCK.getCode(),10);
                        Result result1 = sconfigFeign.updateMapnum(sconfig.getId(),"Bearer "+UPDATEMAKTOKEN);
                        if(!result1.isFlag()){
                            redisUtils.unlook(NoahEnum.GPSLOCK.getCode());
                            continue;
                        }
                        Result result = sconfigFeign.getMapnum("0","Bearer "+GETMAKTOKEN);
                        if(!result.isFlag()){
                            redisUtils.unlook(NoahEnum.GPSLOCK.getCode());
                            continue;
                        }
                        Map map = (Map) result.getData();
                        Sconfig sconfig1 = new Sconfig();
                        sconfig1.setId(Long.parseLong(map.get("id").toString()));
                        sconfig1.setMapkey(map.get("mapkey").toString());
                        sconfig1.setState( map.get("state").toString());
                        sconfig1.setType(map.get("type").toString());
                        boolean res = redisUtils.set(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSKEY.getCode(),sconfig1);
                        redisUtils.del(NoahEnum.GPSKEYDIR.getCode()+NoahEnum.GPSNUMKEY.getCode());
                        redisUtils.unlook(NoahEnum.GPSLOCK.getCode());
                        mapkey = map.get("mapkey").toString();
                    }

                    //GPS坐标转高德系坐标
                    String gps = otherMapFeign.getGDLocation(mapkey, s, "gps");
                    String locations = JSONObject.parseObject(gps).getString("locations");
                    //获取详情
                    String base = otherMapFeign.getLocationInfo(mapkey, locations, "base");
                    JSONObject regeocode = JSONObject.parseObject(base).getJSONObject("regeocode");
                    String devdesc = regeocode.getString("formatted_address");//位置详情
                    JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                    String city = addressComponent.getString("city");//城市
                    String province = addressComponent.getString("province");//省
                    String adcode = addressComponent.getString("adcode");//区域代码
                    String street = addressComponent.getJSONObject("streetNumber").getString("street");//街道
                    String country = addressComponent.getString("country");//国家
                    String citycode = addressComponent.getString("citycode");//城市代码
                    if(StringUtils.isEmpty(locations)){
                        continue;
                    }

                    Site site = new Site();
                    site.setImei(imei);
                    site.setSite(locations);
                    site.setModel("B2315+");
                    site.setProd("OUFU");
                    site.setTs(date);
                    int i = siteMapper.insert(site);
                    String point = siteMapper.getSite(imei);
                    poFence(imei,locations,point);

                }else if(keyname.equals("F6")){
                    //心跳包解析 解析电量，步数，信号强度
                    BigInteger bigInteger = new BigInteger(backdate.substring(4,6)+backdate.substring(2,4),16);
                    String elect = String.valueOf(bigInteger.intValue());//电量
                    BigInteger bigInteger1 = new BigInteger(backdate.substring(12,14)+backdate.substring(10,12)+backdate.substring(8,10)+backdate.substring(6,8),16);
                    String step = String.valueOf(bigInteger1.intValue());//步数
                    BigInteger bigInteger2 = new BigInteger(backdate.substring(14,16),16);
                    String signal = String.valueOf(bigInteger2.intValue());//信号强度
                    //步数存储数据库
                    Step step1 = new Step();
                    step1.setImei(imei);
                    step1.setStep(step);
                    step1.setModel("B2315+");
                    step1.setProd("OUFU");
                    step1.setTs(date);
                    int i = stepMapper.insert(step1);

                    Sp sp = spMapper.selectImei(imei);
                    Sp newSp = new Sp();
                    if(ObjectUtils.isEmpty(sp)){
                        newSp.setTs(date);
                    }else{
                        newSp.setTs(sp.getTs());
                    }

                    String sp1 = null;
                    if("0".equals(elect)){
                        sp1 = "10";
                    }else if("1".equals(elect)){
                        sp1 = "30";
                    }else if("2".equals(elect)){
                        sp1 = "60";
                    }else if("3".equals(elect)){
                        sp1 = "100";
                    }

                    newSp.setImei(imei);
                    newSp.setModel("B2315+");
                    newSp.setProd("OUFU");
                    newSp.setSp(sp1);
                    newSp.setType("1");
                    int i1 = spMapper.insertImei(newSp);
                    Semaphore semaphore = semaphoreMapper.selectImei(imei);
                    Semaphore newSemaphore = new Semaphore();
                    if(ObjectUtils.isEmpty(semaphore)){
                        newSemaphore.setTs(date);
                    }else {
                        newSemaphore.setTs(semaphore.getTs());
                    }
                    newSemaphore.setImei(imei);
                    newSemaphore.setModel("B2315+");
                    newSemaphore.setProd("OUFU");
                    newSemaphore.setSemaphore(signal);
                    newSemaphore.setType("1");
                    int a = semaphoreMapper.insertImei(newSemaphore);

                }else if(keyname.equals("02")){
                    BigInteger bigInteger = new BigInteger(backdate.substring(4,6)+backdate.substring(2,4),16);
                    String state = Integer.toBinaryString(bigInteger.intValue());//报警信息解析
                    int code = state.length() - 1;
                    Dstatus dstatus1 = dstatusMapper.selectImei(imei);
                    if(code == 2){
                        Dstatus dstatus = new Dstatus();
                        if (ObjectUtils.isEmpty(dstatus1)){
                            dstatus.setTs(date);
                        }else {
                            dstatus.setTs(dstatus1.getTs());
                        }
                        dstatus.setImei(imei);
                        dstatus.setProd("OUFU");
                        dstatus.setModel("B2315+");
                        dstatus.setType("1");
                        dstatus.setStatus("N");
                        int i = dstatusMapper.insertImei(dstatus);
                    }
                    String msg1 = null;
                    String type = null;
                    switch (code){
                        case 0:
                            msg1 = "低电量报警";
                            type = "low";
                            break;
                        case 1:
                            msg1 = "SOS紧急报警";
                            type = "sos";
                            break;
                        case 2:
                            msg1 = "关机报警";
                            type = "shutdown";
                            break;
                        case 3:
                            msg1 = "开箱报警";
                            type = "open";
                            break;
                        case 4:
                            msg1 = "摘掉手环报警";
                            type = "remove";
                            break;
                        case 5:
                            msg1 = "久坐报警";
                            type = "burn";
                            break;
                        case 6:
                            msg1 = "震动报警";
                            type = "shake";
                            break;
                        case 7:
                            msg1 = "SOS警报取消";
                            type = "sosoff";
                            break;
                        case 8:
                            msg1 = "设备佩戴通知";
                            type = "wear";
                            break;
                        case 9:
                            msg1 = "松开键";
                            type = "loosen";
                            break;
                        default:
                            msg1 = "未知警报类型";
                            type = "other";
                            break;
                        }

                    Alarm alarm = new Alarm();
                    alarm.setImei(imei);
                    alarm.setAlarm(msg1);
                    alarm.setType(type);
                    alarmFeign.addAlarm( alarm,"Bearer "+TOKEN);
                }else if(keyname.equals("C6")){
                    BigInteger bigInteger = new BigInteger(backdate.substring(2,4),16);
                    String oxi = String.valueOf(bigInteger.intValue());//血氧
                }else if(keyname.equals("C3")){
                    BigInteger bigInteger = new BigInteger(backdate.substring(4,6)+backdate.substring(2,4),16);
                    String charge = String.valueOf(bigInteger.intValue());//充电状态
                }else if(keyname.equals("A3")){
                    //wifi和基站信息上传
                    String location = "";
                    if(!backdate.substring(12,14).equals("00")){
                        int cont = Integer.parseInt(backdate.substring(12,14));
                        int x = 0;
                        String macs ="";
                        for(int i = 0;i < cont ; i++){
                            String mac = backdate.substring(14+x,16+x);
                            int y = 2;
                            for(int a = 0;a <= 4;a++){
                                mac = mac + ":" + backdate.substring(14+x+y,16+x+y);
                                y = y + 2;
                            }
                            BigInteger bigInteger = new BigInteger(backdate.substring(26+x, 28+x), 16);
                            String signal = Integer.toBinaryString(bigInteger.intValue());//信号强度解析
                            String sign = getSign(signal);
                            if(backdate.substring(12,14).equals("01")){
                                macs = mac+","+sign+","+String.valueOf(i+1);
                            }else {
                                if(i == 0){
                                    macs = mac+","+sign+","+String.valueOf(i+1);
                                }else{
                                    macs = macs +"|"+mac+","+sign+","+String.valueOf(i+1);
                                }
                            }
                            x = x + 20;
                        }

                        //动态去mapkey值
                        boolean keyres = redisUtils.hasKey(NoahEnum.MAPKEYDIR.getCode()+ NoahEnum.MAPKEY.getCode());
                        if(!keyres){
                            Result result = sconfigFeign.getMapnum("0","Bearer "+GETMAKTOKEN);
                            if(!result.isFlag()){
                                redisUtils.unlook(NoahEnum.MAPLOCK.getCode());
                                continue;
                            }
                            Map map = (Map) result.getData();
                            Sconfig sconfig1 = new Sconfig();
                            sconfig1.setId(Long.parseLong(map.get("id").toString()));
                            sconfig1.setMapkey(map.get("mapkey").toString());
                            sconfig1.setState( map.get("state").toString());
                            sconfig1.setType(map.get("type").toString());
                            boolean res = redisUtils.set(NoahEnum.MAPKEYDIR.getCode()+NoahEnum.MAPKEY.getCode(),sconfig1);
                            if(!res){
                                continue;
                            }
                        }
                        Object object = redisUtils.getValue(NoahEnum.MAPKEYDIR.getCode()+ NoahEnum.MAPKEY.getCode());
                        Sconfig sconfig = (Sconfig) object;
                        Long number  = redisUtils.incr(NoahEnum.MAPKEYDIR.getCode()+NoahEnum.MAPNUMKEY.getCode(),1);
                        String mapkey = sconfig.getMapkey();
                        if(number > 2900000){
                            redisUtils.lock(NoahEnum.MAPLOCK.getCode(),10);
                            Result result1 = sconfigFeign.updateMapnum(sconfig.getId(),"Bearer "+UPDATEMAKTOKEN);
                            if(!result1.isFlag()){
                                redisUtils.unlook(NoahEnum.MAPLOCK.getCode());
                                continue;
                            }
                            Result result = sconfigFeign.getMapnum("0","Bearer "+GETMAKTOKEN);
                            if(!result.isFlag()){
                                redisUtils.unlook(NoahEnum.MAPLOCK.getCode());
                                continue;
                            }
                            Map map = (Map) result.getData();
                            Sconfig sconfig1 = new Sconfig();
                            sconfig1.setId(Long.parseLong(map.get("id").toString()));
                            sconfig1.setMapkey(map.get("mapkey").toString());
                            sconfig1.setState( map.get("state").toString());
                            sconfig1.setType(map.get("type").toString());
                            boolean res = redisUtils.set(NoahEnum.MAPKEYDIR.getCode()+NoahEnum.MAPKEY.getCode(),sconfig1);
                            redisUtils.del(NoahEnum.MAPKEYDIR.getCode()+NoahEnum.MAPNUMKEY.getCode());
                            redisUtils.unlook(NoahEnum.MAPLOCK.getCode());
                            mapkey = map.get("mapkey").toString();
                        }

                        //解析返回数据
                        location = otherGetMapFeign.getLocationmacs(mapkey,"1","0","GSM",macs,imei);
                        JSONObject result = JSON.parseObject(location);
                        String infocode = result.getString("infocode");
                        result = JSON.parseObject(location);
                        String rtype = result.getJSONObject("result").getString("type");
                        String loca = result.getJSONObject("result").getString("location");
                        if(StringUtils.isEmpty(loca)){
                            continue;
                        }

                        Site site = new Site();
                        site.setTs(date);
                        site.setProd("OUFU");
                        site.setModel("B2315+");
                        site.setSite(loca);
                        site.setImei(imei);
                        int i = siteMapper.insert(site);

                        String point = siteMapper.getSite(imei);
                        poFence(imei,loca,point);

                    }
                }else if(keyname.equals("F3")){
                    String iccid = backdate.substring(2,22);
                    Example example = new Example(Dstatus.class);
                    example.createCriteria().orEqualTo(example);
                    Dstatus dstatus = dstatusMapper.selectImei(imei);
                    Dstatus newDstatus = new Dstatus();
                    if(ObjectUtils.isEmpty(dstatus)){
                        newDstatus.setTs(date);
                    }else {
                        newDstatus.setTs(dstatus.getTs());
                    }
                    newDstatus.setStatus("Y");
                    newDstatus.setType("1");
                    newDstatus.setModel("B2315+");
                    newDstatus.setProd("OUFU");
                    newDstatus.setImei(imei);
                    int i = dstatusMapper.insertImei(newDstatus);
                }else if(keyname.equals("C5")){
                    //睡眠时间解析

                    BigInteger bigInteger = new BigInteger(backdate.substring(28,30)+backdate.substring(26,28)+backdate.substring(24,26)+backdate.substring(22,24),16);
                    String type = bigInteger.toString();
                    BigInteger bigInteger2 = new BigInteger(backdate.substring(8,10)+backdate.substring(6,8)+backdate.substring(4,6)+backdate.substring(2,4),16);
                    Date startts = new Date(Long.parseLong(bigInteger2.toString()) * 1000);
                    BigInteger bigInteger3 = new BigInteger(backdate.substring(16,18)+backdate.substring(14,16)+backdate.substring(12,14)+backdate.substring(10,12),16);
                    Date endts = new Date(Long.parseLong(bigInteger3.toString()) * 1000);

                    BigInteger bigInteger1 = new BigInteger(backdate.substring(20,22)+backdate.substring(18,20),16);
                    String longtime = String.valueOf(bigInteger1.intValue());
                    Sleep sleep = new Sleep();
                    sleep.setImei(imei);
                    sleep.setModel("B2315+");
                    sleep.setProd("OUFU");
                    sleep.setTs(date);
                    sleep.setType(type);
                    sleep.setSleep(longtime);
                    sleep.setStartts(startts);
                    sleep.setEndts(endts);
                    int a = sleepMapper.insert(sleep);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反码求原码接口
     * @param signal
     * @return
     */
    public String getSign(String signal){
        String signa = "";
        if(signal.substring(0,1).equals("1")){
            String sig = signal.substring(1,signal.length());
            String sign = "1";
            for(int i = 0; i < sig.length();i++){
                if(sig.substring(i,i+1).equals("1")){
                    sign= sign + "0";
                }else{
                    sign = sign + "1";
                }
            }
            int sig1 = 113 - (Integer.valueOf(sign,2) + 1);
            signa = String.valueOf(sig1);
        }else{
            int i = Integer.parseInt(signal) * 2 - 113;
            signa = String.valueOf(i);
        }
        return signa;
    }

    /**
     * 判断围栏进出报警接口
     * @param imei
     * @param loca
     * @param site
     */
    @Override
    public void poFence(String imei, String loca, String site) {

         if(redisUtils.hasKey(NoahEnum.WORKERSITE.getCode()+imei)){
            IdWorker idWorker = new IdWorker();
            Map<String,Object> map = new HashMap<>();
            map.put("messageid",String.valueOf(idWorker.nextId()));
            map.put("imei",imei);
            map.put("createTime", DateUtil.data2str(new Date(),DateUtil.PATTERN_YYYY_MM_DDHHMM));
            map.put("loca",loca);
            map.put("site",site);
            mqUtil.sendDirectMsg("build","locatekey",map);
        }
        boolean keyres = redisUtils.hasKey(NoahEnum.FENCEDIR.getCode()+imei);
        if(!keyres){
            return;
        }
        List<Object> list1 = redisUtils.lGet(NoahEnum.FENCEDIR.getCode()+imei,0,-1);
        if(ObjectUtils.isEmpty(list1)){
            return;
        }
        for (Object object : list1) {
            Fence fence = (Fence) object;
            if(fence.getStatus().equals("1")){
                continue;
            }

            String[] pointC = fence.getPoint().split(",");
            Double pointCx = Double.parseDouble(pointC[0]);//围栏圆心的经度
            Double pointCy = Double.parseDouble(pointC[1]);//围栏圆心的纬度

            String[] pointloca = loca.split(",");
            Double pointlocax = Double.parseDouble(pointloca[0]); //现在x坐标
            Double pointlocay = Double.parseDouble(pointloca[1]); //现在y坐标

            String[] pointsite = site.split(",");
            Double pointsitex = Double.parseDouble(pointsite[0]); // 上次x坐标
            Double pointsitey = Double.parseDouble(pointsite[1]);//上次y坐标

            double lon1 = (Math.PI / 180) * pointlocax;//最近时间经度
            double lat1 = (Math.PI / 180) * pointlocay;//最近时间纬度

            double lon2 = (Math.PI / 180) * pointsitex;//前一次时间纬度
            double lat2 = (Math.PI / 180) * pointsitey;//前一次时间纬度
            double lonC = (Math.PI / 180) * pointCx;//圆心经度
            double latC = (Math.PI / 180) * pointCy;//圆心纬度

            // 地球半径
            double R = 6378124;

            // 两点间距离 km，如果想要米的话，结果*1000就可以了
            double dstart = Math.acos(Math.sin(lat1) * Math.sin(latC) + Math.cos(lat1) * Math.cos(latC) * Math.cos(lonC - lon1)) * R;//最近时间经纬度到圆心的距离
            double dend = Math.acos(Math.sin(lat2) * Math.sin(latC) + Math.cos(lat2) * Math.cos(latC) * Math.cos(lonC - lon2)) * R;//前一次时间经纬度到圆心的距离
            Map<String,String> map = null;
            Alarm alarm = new Alarm();

            if (fence.getAlarm().equals("0") && (dstart <= fence.getRadius() && dend > fence.getRadius())) {
                //进围栏报警
                //App报警信息-----------
                String msg1 = "进入" + fence.getName() + "围栏报警！";
                String type = "in";
                //异步调用报警feign
                alarm.setImei(imei);
                alarm.setAlarm(msg1);
                alarm.setType(type);
                alarmFeign.addAlarm(alarm,"Bearer "+TOKEN);
            } else if (fence.getAlarm().equals("1") && (dend <= fence.getRadius() && dstart > fence.getRadius())) {
                //出围栏报警
                //App报警信息-----------
                String msg1 = "离开" + fence.getName() + "围栏报警！";
                String type = "out";
                alarm.setImei(imei);
                alarm.setAlarm(msg1);
                alarm.setType(type);
                alarmFeign.addAlarm(alarm,"Bearer "+TOKEN);

            } else if (fence.getAlarm().equals("2")) {
                //进出围栏报警
                if (dstart <= fence.getRadius() && dend > fence.getRadius()) {
                    //进围栏报警
                    //App报警信息-----------
                    String msg1 = "进入" + fence.getName() + "围栏报警！";
                    String type = "in";
                    alarm.setImei(imei);
                    alarm.setAlarm(msg1);
                    alarm.setType(type);
                    alarmFeign.addAlarm(alarm,"Bearer "+TOKEN);

                } else if (dend <= fence.getRadius() && dstart > fence.getRadius()) {
                    //出围栏报警
                    //App报警信息-----------
                    String msg1 = "离开" + fence.getName() + "围栏报警！";
                    String type = "out";
                    alarm.setImei(imei);
                    alarm.setAlarm(msg1);
                    alarm.setType(type);
                    alarmFeign.addAlarm(alarm,"Bearer "+TOKEN);
                    //登记系统信息表
                }
            }
        }
        return;
    }
}
